const fs = require('fs');
const path = require('path');

// 遍历 src 下所有 js / vue 文件
function getAllFiles(dir, files = []) {
  fs.readdirSync(dir).forEach(file => {
    const fullPath = path.join(dir, file);
    if (fs.statSync(fullPath).isDirectory()) {
      getAllFiles(fullPath, files);
    } else if (fullPath.endsWith('.js') || fullPath.endsWith('.vue')) {
      files.push(fullPath);
    }
  });
  return files;
}

// 根据相对 import 路径找到真实文件
function findRealPath(importPath, baseDir) {
  if (!importPath.startsWith('@/')) return null; // 只处理 @/ 开头的别名
  const relativePath = importPath.replace(/^@\//, '');
  const fullDir = path.join(baseDir, 'src', relativePath);

  const extensions = ['.js', '.vue', '.ts', '/index.js', '/index.vue'];
  for (const ext of extensions) {
    const candidate = fullDir.endsWith(ext) ? fullDir : fullDir + ext;
    if (fs.existsSync(candidate)) return importPath; // 已经正确
  }

  // 尝试大小写匹配
  const parts = relativePath.split('/');
  let currentDir = path.join(baseDir, 'src');
  let realParts = [];
  for (const part of parts) {
    if (!fs.existsSync(path.join(currentDir))) break;
    const files = fs.readdirSync(currentDir);
    const matched = files.find(f => f.toLowerCase() === part.toLowerCase());
    if (!matched) return null; // 找不到对应文件夹
    realParts.push(matched);
    currentDir = path.join(currentDir, matched);
  }
  return realParts.length ? '@/' + realParts.join('/') : null;
}

const allFiles = getAllFiles(path.join(__dirname, 'src'));
allFiles.forEach(filePath => {
  let content = fs.readFileSync(filePath, 'utf-8');
  let modified = false;

  const importRegex = /@\/[A-Za-z0-9_\-\/]+/g;
  const matches = content.match(importRegex);
  if (!matches) return;

  matches.forEach(imp => {
    const realPath = findRealPath(imp, __dirname);
    if (realPath && realPath !== imp) {
      content = content.replace(new RegExp(imp, 'g'), realPath);
      modified = true;
      console.log(`🔧 修复 ${filePath}: ${imp} -> ${realPath}`);
    }
  });

  if (modified) {
    fs.writeFileSync(filePath, content, 'utf-8');
  }
});

console.log("🎉 自动修复 import 完成！");

